02. 解决方案: 列表

解决方案: 列表索引

def how_many_days(month_number):
    """Returns the number of days in a month.
    WARNING: This function doesn't account for leap years!
    """
    days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
    #todo: return the correct value
    return days_in_month[month_number - 1]

# This test case should print 31, the number of days in the eighth month, August
print(how_many_days(8))

解决方案: 列表切片

eclipse_dates = ['June 21, 2001', 'December 4, 2002', 'November 23, 2003',
                 'March 29, 2006', 'August 1, 2008', 'July 22, 2009',
                 'July 11, 2010', 'November 13, 2012', 'March 20, 2015',
                 'March 9, 2016']


# TODO: Modify this line so it prints the last three elements of the list
print(eclipse_dates[-3:])

解决方案: 前三名

def top_three(input_list):
    return sorted(input_list, reverse = True)[:3]

解决方案: 中位数

There are two cases the median function needs to handle: inputs with even lengths and inputs with odd lengths. I can use an if statement to determine whether the list's length is even or odd.

python
def median(numbers):
numbers.sort()
if len(numbers) % 2:
# if the list has an odd number of elements,
# the median is the middle element
middle_index = int(len(numbers)/2)
return numbers[middle_index]
else:
# if the list has an even number of elements,
# the median is the average of the middle two elements
right_of_middle = len(numbers)//2
left_of_middle = right_of_middle - 1
return (numbers[right_of_middle] + numbers[left_of_middle])/2